/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.common  
 */
package com.apache.bid.common;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.api.vo.ResultMsg;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidPub;
import com.apache.rpc.client.RpcProtoclClient;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.DateUtils;
import com.apache.tools.DateUtils.FmtStr;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import com.apache.workday.WorkdayUtils;

/**
 * description:  统一处理类（处理状态）
 * @author Hou Dayu 创建时间：2016-3-25  
 * 
 */
public class BidCommonUtil {

	private Logger log = Logger.getLogger(getClass());
	private static BidCommonUtil instance;

	private BidCommonUtil() {
	}

	public void init() {
		instance = this;
	}

	public static BidCommonUtil getInstance() {
		if (null == instance) {
			instance = new BidCommonUtil();
		}
		return instance;
	}

	/**
	 * description:  获取标的状态
	 */
	@SuppressWarnings("rawtypes")
	public String getStatus(BidItemPrice price, String bidTime) throws ParseException {
		String status = "";
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + price.getItemId());
		if (ToolsUtil.isEmpty(itemVo))
			return Constant.getInstance().getItemConfig("unStart");
		switch (BidModeEnum.getName(itemVo.getBidMode())) {
		case JTZX://阶梯正向 
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case JTFX://阶梯反向 
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case YCXASC://一次正向
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case YCXDESC://一次反向
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case FEJJZX://份额正向
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case FEJJFX://份额反向
			status = getItemStatus(price, itemVo, bidTime);
			break;
		case HELAN://荷兰式正向（无反向）
			status = getItemStatus(price, itemVo, bidTime);
			break;
		}
		return status;
	}

	/**
	 * description:  报价条件验证
	 */
	public ResultMsg getCheckItem(String status, String myPrice, String userEname, BidItemCacheVo itemVo,
			BidItemPrice price) {
		ResultMsg msg = null;
		switch (BidModeEnum.getName(itemVo.getBidMode())) {
		case JTZX://阶梯正向 
			msg = basisCheckItem(status, myPrice, userEname, itemVo, price);
			break;
		case JTFX://阶梯反向 
			msg = basisCheckItemFx(status, myPrice, userEname, itemVo, price);
			break;
		case YCXASC://一次正向
			msg = checkOnceBaojia(status, myPrice, userEname, itemVo, price);
			break;
		case YCXDESC://一次反向
			msg = checkOnceBaojiaFx(status, myPrice, userEname, itemVo, price);
			break;
		case FEJJZX://份额正向
			msg = checkOnceBaojia(status, myPrice, userEname, itemVo, price);
			break;
		case FEJJFX://份额反向
			msg = checkOnceBaojiaFx(status, myPrice, userEname, itemVo, price);
			break;
		case HELAN://荷兰式正向（无反向）
			msg = basisCheckItem(status, myPrice, userEname, itemVo, price);
			break;
		}
		return msg;
	}

	/**
	 * description:  计算标的当前过程虚状态
	 * <entry key="unStart" value="A" /><!-- 未开始 -->
	    <entry key="freeOffer" value="B" /><!-- 自由报价期 -->
	    <entry key="limitedOffer" value="C" /><!-- 限时报价期 -->
	    <entry key="increase" value="D" /><!-- 加价期 -->
	    <entry key="exercise" value="E" /><!-- 行权期 -->
	 */
	public String getItemStatus(BidItemPrice price, BidItemCacheVo itemVo, String bidTime) throws ParseException {

		if (!Constant.getInstance().getItemConfig("statusPubslish").equals(itemVo.getItemStatus())) {
			if (Constant.getInstance().getItemConfig("statusStop").equals(itemVo.getItemStatus())) {
				if (Constant.SETYPE_HD.equals(itemVo.getSessionType())) {//结束时清掉锁
					Constant.getInstance().removeJingjiaMapByKey(itemVo.getItemId());
				}
			}
			return itemVo.getItemStatus();
		}
		//系统当前时间
		long nowTime = getMillTime(bidTime, FmtStr.yyyyMMdd_HHmmssSSS.toString());
		//自由竞价开始时间
		long opentime = getMillTime(price.getOpenTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		if (opentime >= nowTime) {
			return Constant.getInstance().getItemConfig("unStart");//A
		}
		//自由竞价结束时间
		long firsttime = getMillTime(price.getFirstBidTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		if (nowTime >= opentime && nowTime < firsttime) {
			return Constant.getInstance().getItemConfig("freeOffer");// 自由竞价期 B
		}
		/**
		 * 延牌条件：设置了自动延牌、并且无报价、还没延到延牌截止时间
		 */
		if ("F".equals(itemVo.getDelayControl()) || !"0".equals(price.getBidTimes())
				|| "T".equals(price.getDelayEndFlag())) {//不延牌

		} else {
			String ddt = StrUtil.doNull(itemVo.getDelayDeadTime(), "");
			long maxDelay = 0;
			if (ddt.length() != 19) {
				maxDelay = getMillTime(Constant.DeayDefaultTime, FmtStr.yyyyMMdd_HHmmss.toString());
			} else {
				maxDelay = getMillTime(StrUtil.doNull(itemVo.getDelayDeadTime(), ""), FmtStr.yyyyMMdd_HHmmss.toString());
			}
			if (firsttime < maxDelay && "F".equals(price.getDelayEndFlag())) {
				String delayStatus = delay(itemVo, price, nowTime);
				return delayStatus;
			}
		}

		long closetime = getMillTime(price.getCloseTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		if (Constant.BIDMODE_HELAN.equals(itemVo.getBidMode())) {//荷兰式
			closetime = getMillTime(price.getReductionCloseTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		}
		if (nowTime >= firsttime && nowTime < closetime) {
			return Constant.getInstance().getItemConfig("limitedOffer");//B
		}
		if (!"T".equals(itemVo.getAllowEndPrio())) {//是否允许事后行权
			stopItemInfo(itemVo, price, "endItem");
			return Constant.getInstance().getItemConfig("ending");
		} else {
			return xingQuan(itemVo, price, nowTime);
		}
	}

	/**
	 * description: 验证一次报价  
	 */
	public ResultMsg checkOnceBaojia(String status, String myPrice, String userEname, BidItemCacheVo itemVo,
			BidItemPrice price) {
		ResultMsg msg = null;
		if (Constant.getInstance().getItemConfig("freeOffer").equals(status)
				|| Constant.getInstance().getItemConfig("limitedOffer").equals(status)
				|| Constant.getInstance().getItemConfig("increase").equals(status)
				|| Constant.getInstance().getItemConfig("exercise").equals(status)) {
		} else {
			msg = new ResultMsg("F", "不在报价期间内，不能报价");
			return msg;
		}
		String applyStr = BidValidatorUtil.getInstance().checkApply(itemVo.getSessionType(), itemVo.getSessionId(),
				itemVo.getItemId(), userEname, price.getFirstValue());
		if (ToolsUtil.isNotNull(applyStr)) {
			msg = new ResultMsg("F", applyStr);
			return msg;
		}
		if (Constant.BIDMODE_YCXASC.equals(itemVo.getBidMode())) {
			String baojiaStr = BidValidatorUtil.getInstance().checkBaojia(userEname, itemVo.getItemId(),
					StrUtil.doNull(itemVo.getAllowUpdateTimes(), "0"));
			if (ToolsUtil.isNotNull(baojiaStr)) {
				msg = new ResultMsg("F", baojiaStr);
				return msg;
			}
		}
		BigDecimal myPrices = new BigDecimal(myPrice);
		BigDecimal nowPrice = new BigDecimal(price.getFirstValue());
		if (myPrices.compareTo(nowPrice) < 0) {
			msg = new ResultMsg("F", "您的报价不高于启始价");
			return msg;
			//		} else if (myPrices == nowPrice) {
		} else if (myPrices.compareTo(nowPrice) == 0) {
			if ("0".equals(StrUtil.doNull(price.getBidTimes(), "0"))) {
				if ("T".equals(itemVo.getAllowFirstValue())) {//是否允许举牌，即是否允许以起始价出价（T/F),缺省T
					return null;
				}
			}
			if ("F".equals(itemVo.getIfRight())) {
				msg = new ResultMsg("F", "您的价格不高于启始价");
				return msg;
			}
		}
		return msg;
	}

	/**
	 * description: 验证一次报价  
	 */
	public ResultMsg checkOnceBaojiaFx(String status, String myPrice, String userEname, BidItemCacheVo itemVo,
			BidItemPrice price) {
		ResultMsg msg = null;
		if (Constant.getInstance().getItemConfig("freeOffer").equals(status)
				|| Constant.getInstance().getItemConfig("limitedOffer").equals(status)
				|| Constant.getInstance().getItemConfig("increase").equals(status)
				|| Constant.getInstance().getItemConfig("exercise").equals(status)) {
		} else {
			msg = new ResultMsg("F", "不在报价期间内，不能报价");
			return msg;
		}
		String applyStr = BidValidatorUtil.getInstance().checkApply(itemVo.getSessionType(), itemVo.getSessionId(),
				itemVo.getItemId(), userEname, price.getFirstValue());
		if (ToolsUtil.isNotNull(applyStr)) {
			msg = new ResultMsg("F", applyStr);
			return msg;
		}
		if (Constant.BIDMODE_YCXDESC.equals(itemVo.getBidMode())) {
			String baojiaStr = BidValidatorUtil.getInstance().checkBaojia(userEname, itemVo.getItemId(),
					StrUtil.doNull(itemVo.getAllowUpdateTimes(), "0"));
			if (ToolsUtil.isNotNull(baojiaStr)) {
				msg = new ResultMsg("F", baojiaStr);
				return msg;
			}
		}
		BigDecimal myPrices = new BigDecimal(myPrice);
		BigDecimal nowPrice = new BigDecimal(price.getFirstValue());
		if (myPrices.compareTo(nowPrice) > 0) {
			msg = new ResultMsg("F", "您的报价不能高于启始价");
			return msg;
			//		} else if (myPrices == nowPrice) {
		} else if (myPrices.compareTo(nowPrice) == 0) {
			if ("0".equals(StrUtil.doNull(price.getBidTimes(), "0"))) {
				if ("T".equals(itemVo.getAllowFirstValue())) {//是否允许举牌，即是否允许以起始价出价（T/F),缺省T
					return null;
				}
			}
			if ("F".equals(itemVo.getIfRight())) {
				msg = new ResultMsg("F", "您的价格不能高于启始价");
				return msg;
			}
		}
		//最小价格
		//float minPrice = Float.parseFloat(StrUtil.doNull(itemVo.getFallLowerstPrice(), itemVo.getHoldvalue()));//
		return msg;
	}

	/**
	 * description:  报价条件验证
	 */
	public ResultMsg basisCheckItem(String status, String myPrice, String userEname, BidItemCacheVo itemVo,
			BidItemPrice price) {
		ResultMsg msg = null;
		if (Constant.getInstance().getItemConfig("freeOffer").equals(status)
				|| Constant.getInstance().getItemConfig("limitedOffer").equals(status)
				|| Constant.getInstance().getItemConfig("increase").equals(status)
				|| Constant.getInstance().getItemConfig("exercise").equals(status)) {
		} else {
			msg = new ResultMsg("F", "不在报价期间内，不能报价");
			return msg;
		}
		String applyStr = BidValidatorUtil.getInstance().checkApply(itemVo.getSessionType(), itemVo.getSessionId(),
				itemVo.getItemId(), userEname, price.getFirstValue());
		if (ToolsUtil.isNotNull(applyStr)) {
			msg = new ResultMsg("F", applyStr);
			return msg;
		}
		if ("F".equals(itemVo.getAllowRepeat())) {//是否允许连续报价（T/F),缺省F
			if (userEname.equals(price.getUserName())) {
				msg = new ResultMsg("F", "您已是最高价，不能继续报价");
				return msg;
			}
		}
		//////判断价格有效性
		BigDecimal myPrices = new BigDecimal(myPrice);
		BigDecimal nowPrice = new BigDecimal(
				StrUtil.doNull(price.getLastValue(), "0").equals("0") ? price.getFirstValue() : price.getLastValue());

		if (myPrices.compareTo(nowPrice) < 0) {
			msg = new ResultMsg("F", "您的价格不高于当前报价");
			return msg;
		} else if (myPrices.compareTo(nowPrice) == 0) {
			if (!Constant.BIDMODE_HELAN.equals(itemVo.getBidMode())) {
				if ("0".equals(StrUtil.doNull(price.getBidTimes(), "0"))) {
					if ("T".equals(itemVo.getAllowFirstValue()) || "T".equals(itemVo.getvFlag())) {//是否允许举牌，即是否允许以起始价出价（T/F),缺省T
						return null;
					}
				}
				if ("F".equals(itemVo.getIfRight())) {
					msg = new ResultMsg("F", "您的价格不高于当前报价");
					return msg;
				}
				String vipKey = BidValidatorUtil.getInstance().checkItemVip(userEname, itemVo.getItemId(),
						price.getLastRightLevel());
				if (ToolsUtil.isNotNull(vipKey)) {
					msg = new ResultMsg("F", vipKey);
					return msg;
				}
			} else {//荷兰式竞价处理
				int bidTimes = Integer.parseInt(StrUtil.doNull(price.getBidTimes(), "0"));
				int itemNum = Integer.parseInt(StrUtil.doNull(itemVo.getItemNum(), "1"));
				BigDecimal fall_lowerst_price = new BigDecimal(StrUtil.doNull(itemVo.getFallLowerstPrice(), "0"));
				BigDecimal bidValue = new BigDecimal(StrUtil.doNull(price.getFirstValue(), "0"));
				if (bidTimes == itemNum || bidValue.compareTo(fall_lowerst_price) < 0) {//判断是否应该结束了
					msg = new ResultMsg("F", "结果处理中，不能继续报价");
					return msg;
				}
			}
		} else {
			//////判断价格浮度有效性
			if ("0".equals(StrUtil.doNull(itemVo.getOncevalue(), "0"))) {//判断是否一口价
				BigDecimal differPrice = myPrices.subtract(nowPrice);
				BigDecimal minValue = checkIncrementValue(itemVo.getIncrementGroup(), itemVo.getIncrementValue(),
						nowPrice);
				if (differPrice.compareTo(minValue) < 0) {
					msg = new ResultMsg("F", "加价必须大于加价幅度");
					return msg;
				}
			}
		}

		return msg;
	}

	private BigDecimal checkIncrementValue(String incrementGroup, String incrementValue, BigDecimal lastValue) {
		BigDecimal increment = new BigDecimal("0");
		if (incrementValue.indexOf('|') == -1) {
			increment = new BigDecimal(incrementValue);
			return increment;
		} else {
			String[] incrementGroupArray = incrementGroup.split("\\|");//1000|2000
			String[] incrementArray = incrementValue.split("\\|");//100|200
			for (int i = incrementGroupArray.length - 1; i >= 0; i--) {
				if (StrUtil.isNull(incrementGroupArray[i])) {
					increment = new BigDecimal(incrementArray[0]);
					return increment;
				}
				if (lastValue.compareTo(new BigDecimal(incrementGroupArray[i])) >= 0) {
					increment = new BigDecimal(incrementArray[i]);
					return increment;
				}
			}
		}
		return increment;
	}

	/**
	 * description:  报价条件验证
	 */
	public ResultMsg basisCheckItemFx(String status, String myPrice, String userEname, BidItemCacheVo itemVo,
			BidItemPrice price) {
		ResultMsg msg = null;
		if (Constant.getInstance().getItemConfig("freeOffer").equals(status)
				|| Constant.getInstance().getItemConfig("limitedOffer").equals(status)
				|| Constant.getInstance().getItemConfig("increase").equals(status)
				|| Constant.getInstance().getItemConfig("exercise").equals(status)) {
		} else {
			msg = new ResultMsg("F", "不在报价期间内，不能报价");
			return msg;
		}
		String applyStr = BidValidatorUtil.getInstance().checkApply(itemVo.getSessionType(), itemVo.getSessionId(),
				itemVo.getItemId(), userEname, price.getFirstValue());
		if (ToolsUtil.isNotNull(applyStr)) {
			msg = new ResultMsg("F", applyStr);
			return msg;
		}
		if ("F".equals(itemVo.getAllowRepeat())) {//是否允许连续报价（T/F),缺省F
			if (userEname.equals(price.getUserName())) {
				msg = new ResultMsg("F", "您已是最高价，不能继续报价");
				return msg;
			}
		}
		//////判断价格有效性
		BigDecimal myPrices = new BigDecimal(myPrice);//Double.valueOf(myPrice);
		BigDecimal nowPrice = new BigDecimal(
				StrUtil.doNull(price.getLastValue(), "0").equals("0") ? price.getFirstValue() : price.getLastValue());//Double.valueOf(price.getLastValue().equals("0") ? price.getFirstValue() : price.getLastValue());
		if (myPrices.compareTo(nowPrice) > 0) {
			msg = new ResultMsg("F", "您的价格不能高于当前报价");
			return msg;
			//		} else if (myPrices == nowPrice) {
		} else if (myPrices.compareTo(nowPrice) == 0) {
			if ("0".equals(StrUtil.doNull(price.getBidTimes(), "0"))) {
				if ("T".equals(itemVo.getAllowFirstValue()) || "T".equals(itemVo.getvFlag())) {//是否允许举牌，即是否允许以起始价出价（T/F),缺省T
					return null;
				}
			}
			if ("F".equals(itemVo.getIfRight())) {
				msg = new ResultMsg("F", "您的价格不能高于当前报价");
				return msg;
			}
			String vipKey = BidValidatorUtil.getInstance().checkItemVip(userEname, itemVo.getItemId(),
					price.getLastRightLevel());
			if (ToolsUtil.isNotNull(vipKey)) {
				msg = new ResultMsg("F", vipKey);
				return msg;
			}
		} else {
			//最小价格
			//float minPrice = Float.parseFloat(StrUtil.doNull(itemVo.getFallLowerstPrice(), itemVo.getHoldvalue()));//
			//////判断价格浮度有效性
			if ("0".equals(StrUtil.doNull(itemVo.getOncevalue(), "0"))) {//判断是否一口价
				BigDecimal differPrice = nowPrice.subtract(myPrices);
				BigDecimal minValue = checkIncrementValue(itemVo.getIncrementGroup(), itemVo.getIncrementValue(),
						nowPrice);
				if (differPrice.compareTo(minValue) < 0) {
					msg = new ResultMsg("F", "降价必须大于降价幅度");
					return msg;
				}
			}
		}

		return msg;
	}

	/**
	 * description:  行权状态处理
	 */
	private String xingQuan(BidItemCacheVo itemVo, BidItemPrice price, long nowTime) throws ParseException {
		long limittime = Long.valueOf(itemVo.getAllowAddTime()) * 60 * 1000;
		Date afterDate = new Date(DateUtils.toLong(DateUtils.parse(price.getCloseTime(), "yyyy-MM-dd HH:mm:ss"))
				+ limittime);
		long addTime = DateUtils.toLong(afterDate);
		if (addTime >= nowTime) {
			if ("T".equals(price.getIfAddPrice())) {
				if ("T".equals(price.getIfPrioFlag())) {////已完成行权后结束标的
					stopItemInfo(itemVo, price, "endItem");
					return Constant.getInstance().getItemConfig("ending");
				}
				return Constant.getInstance().getItemConfig("exercise");//行权期
			}
			return Constant.getInstance().getItemConfig("increase");//加价期
		} else {
			if ("T".equals(price.getIfPrioFlag())) {
				stopItemInfo(itemVo, price, "endItem");
				return Constant.getInstance().getItemConfig("ending");
			}
			limittime = Long.valueOf(itemVo.getAllowPrioTime()) * 60 * 1000;
			long prioTime = addTime + limittime;
			if (prioTime >= nowTime) {
				return Constant.getInstance().getItemConfig("exercise");//行权期
			} else {
				stopItemInfo(itemVo, price, "endItem");
				return Constant.getInstance().getItemConfig("ending");
			}
		}
	}

	/**
	 * 通知缓存服务器，执行终止标的操作
	 * @param itemVo
	 * @param price
	 * @param methodCode
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean stopItemInfo(BidItemCacheVo itemVo, BidItemPrice price, String methodCode) {
		Map params = new HashMap();
		if ("endItem".equals(methodCode)) {
			params.put("itemId", itemVo.getItemId());
		} else if ("editItemPrice".equals(methodCode)) {
			Map map = WbdToolsUtil.getInstance().toMapDelNull(price);
			params.putAll(map);
			if ("Z".equals(itemVo.getItemStatus())) {
				params.put("itemStop", "T");
			}
		}
		if (!"3".equals(itemVo.getSessionType())) {
			params.put("syncObjId", itemVo.getSessionId());
		} else {
			params.put("syncObjId", itemVo.getItemId());
		}
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidPub pub = BidCommonUtil.getInstance().getBidPub(itemVo, cache);
		if (!Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
			params.put("syncObjId", itemVo.getSessionId());
		} else {
			params.put("syncObjId", itemVo.getItemId());
		}
		if (null != pub)
			RpcProtoclClient.getInstance().doService("wbdCacheService", methodCode, params,
					getInterfaceRegister(pub.getBjServer(), pub.getBjPort()));
		else
			RpcProtoclClient.getInstance().doService("wbdCacheService", methodCode, params,
					getInterfaceRegister("", ""));
		return true;
	}

	/**
	 * 延牌处理
	 * description:  自由报价期（firstBidTime)
	 * @param itemVo
	 * @param price
	 * @return   
	 */
	public String delay(BidItemCacheVo itemVo, BidItemPrice price, long nowTime) {
		String objId = itemVo.getItemId();
		long now = System.currentTimeMillis();
		if (!Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
			objId = itemVo.getSessionId();
		}
		Constant.getInstance().setJingjiaMap(objId, objId);
		final String key = Constant.getInstance().getJingjiaMap(objId);
		synchronized (key) {
			long fbtime = getMillTime(price.getFirstBidTime(), FmtStr.yyyyMMdd_HHmmss.toString());
			if (now < fbtime) {
				log.info("delay-confliction: 已延牌;itemname==" + itemVo.getItemName() + "----now=="
						+ DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "(" + now + ")" + "----fbtime=="
						+ price.getFirstBidTime() + "(" + fbtime + ")");
				return Constant.getInstance().getItemConfig("freeOffer");// 自由竞价期
			}
			String ddt = StrUtil.doNull(itemVo.getDelayDeadTime(), "");
			long maxDelay = 0;
			if (ddt.length() != 19) {
				maxDelay = getMillTime(Constant.DeayDefaultTime, FmtStr.yyyyMMdd_HHmmss.toString());
			} else {
				maxDelay = getMillTime(StrUtil.doNull(itemVo.getDelayDeadTime(), ""), FmtStr.yyyyMMdd_HHmmss.toString());
			}

			long temp = now;
			if (temp > maxDelay) {
				temp = maxDelay;
			}
			String delayUnit = StrUtil.doNull(itemVo.getDelayUnit(), "h");//小时
			int tt = 0;
			String delayPerTrue = "";
			String delayPer = StrUtil.doNull(itemVo.getDelayPeriod(), "1");
			if (!"1".equals(delayPer)) {
				String decres[] = delayPer.split(",");
				int delaynumber = StrUtil.isNull(price.getDelayTimes()) ? 0 : Integer.valueOf(price.getDelayTimes());
				if (delaynumber > decres.length - 1) {
					delayPerTrue = decres[decres.length - 1];
				} else {
					delayPerTrue = decres[delaynumber];
				}
			}
			int delayPeriod_Hour = Integer.valueOf(StrUtil.doNull(delayPerTrue, "1"));

			if (!"wd".equals(delayUnit)) {
				//延牌周期：小时数
				int sec = 3600;
				if ("m".equals(delayUnit)) {
					sec = 60;
				} else if ("d".equals(delayUnit)) {
					sec = 3600 * 24;
				}
				//延牌周期：毫秒数
				long delayPeriod = 0L;
				if (delayPeriod_Hour > 0) {
					delayPeriod = delayPeriod_Hour * sec * 1000;
				} else {
					delayPeriod = 1;
				}

				tt = (int) ((temp - fbtime) / delayPeriod);
				fbtime = fbtime + (tt + 1) * delayPeriod;
			} else { //工作日延牌
				String h_m_s = price.getFirstBidTime().substring(10);
				try {
					String inputFb = price.getFirstBidTime().substring(0, 11);//
					String workdaystr = WorkdayUtils.getInstance().afterWorkday(inputFb, delayPeriod_Hour);
					workdaystr = workdaystr.substring(0, 4) + "-" + workdaystr.substring(4, 6) + "-"
							+ workdaystr.substring(6, 8);
					String newFirstbidtime = workdaystr + h_m_s;
					fbtime = DateUtils.toLong(DateUtils.parse(newFirstbidtime, "yyyy-MM-dd HH:mm:ss"));
					tt = 1;
					boolean b = true;
					while (b) {
						if (fbtime < temp) {
							workdaystr = WorkdayUtils.getInstance().afterWorkday(workdaystr, delayPeriod_Hour);
							workdaystr = workdaystr.substring(0, 4) + "-" + workdaystr.substring(4, 6) + "-"
									+ workdaystr.substring(6, 8);
							newFirstbidtime = workdaystr + h_m_s;
							fbtime = DateUtils.toLong(DateUtils.parse(newFirstbidtime, "yyyy-MM-dd HH:mm:ss"));
							tt++;
						} else {
							b = false;
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}//工作日延牌

			boolean endFlag = false;//延牌肯定结束
			if (fbtime >= maxDelay) {
				fbtime = maxDelay;
				endFlag = true;
			}
			//2012-07-12 延牌过程中起始价降低；---
			String decre = StrUtil.doNull(itemVo.getFallDecrement(), "0");
			boolean isEndForDecre = false;
			if (!"0".equals(decre)) {
				String decres[] = decre.split(",");
				int delaynumber = StrUtil.isNull(price.getDelayTimes()) ? 0 : Integer.valueOf(price.getDelayTimes());
				String decreTrue = "";
				if (delaynumber > decres.length - 1) {
					decreTrue = decres[decres.length - 1];
				} else {
					decreTrue = decres[delaynumber];
				}
				double newFirstprice = 0; //新的起始价
				double lowerstp = Double.parseDouble(itemVo.getFallLowerstPrice());
				double firstp = Double.parseDouble(StrUtil.doNull(price.getFirstValue(), itemVo.getFirstValuePre()));
				if (firstp > lowerstp) {
					newFirstprice = firstp - ((tt + 1) * Double.parseDouble(decreTrue));
					if (newFirstprice <= lowerstp) {
						newFirstprice = lowerstp;
						//if("2050-01-01 10:10:00".equals(vo.getDelayDeadTime())){
						price.setDelayEndFlag("T");
						isEndForDecre = true;
						//}
					}
				}
				int decCount = Integer.parseInt(itemVo.getDecimalCount());
				String newFirstpriceS = NumberUtils.format(newFirstprice, decCount, false);
				price.setFirstValue(newFirstpriceS);
			}

			//2009-20-21改动
			Integer delayNumber = new Integer(tt + 1);
			String dealTimesStr = StrUtil.doNull(price.getDelayTimes(), "0");
			int dealTimes = delayNumber + Integer.valueOf(dealTimesStr);
			price.setDelayTimes(String.valueOf(dealTimes));//第几次延牌
			int limitTime = Integer.valueOf(StrUtil.doNull(itemVo.getLimitTime(), "0")) * 1000;
			if (now >= maxDelay + limitTime) {//结束
				price.setFirstBidTime(DateUtils.longToStr(maxDelay, FmtStr.yyyyMMdd_HHmmss));
				price.setCloseTime(DateUtils.longToStr(maxDelay + limitTime, FmtStr.yyyyMMdd_HHmmss));

				/**标识为延牌结束 2010-12-01*/
				price.setDelayEndFlag("T");
				itemVo.setItemStatus("Z");
				stopItemInfo(itemVo, price, "editItemPrice");

				return "9";// 直接已经结束
			} else if (now >= maxDelay) {//限时
				price.setFirstBidTime(DateUtils.longToStr(maxDelay, FmtStr.yyyyMMdd_HHmmss));
				price.setCloseTime(DateUtils.longToStr(maxDelay + limitTime, FmtStr.yyyyMMdd_HHmmss));
				/**标识为延牌结束 2010-12-01*/
				price.setDelayEndFlag("T");
				stopItemInfo(itemVo, price, "editItemPrice");

				return "C";// 进入限时报价期
			} else {
				//正常每次延控制
				if (endFlag) {
					/**标识为延牌结束 2010-12-01*/
					price.setDelayEndFlag("T");
				}
				price.setFirstBidTime(DateUtils.longToStr(fbtime, FmtStr.yyyyMMdd_HHmmss));
				if (isEndForDecre) {
					price.setCloseTime(DateUtils.longToStr(fbtime, FmtStr.yyyyMMdd_HHmmss));
				} else {
					price.setCloseTime(DateUtils.longToStr(fbtime + limitTime, FmtStr.yyyyMMdd_HHmmss));
				}
				stopItemInfo(itemVo, price, "editItemPrice");

				return "B";// 自由报价期
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public BidPub getBidPub(BidItemCacheVo item, BidCacheManager cache) {
		BidPub pub = null;
		if ("0".equals(item.getSessionId())) {
			pub = (BidPub) cache.getCacheObjectByKey(BidCacheManager.pub_prefix + item.getItemId());
		} else {
			pub = (BidPub) cache.getCacheObjectByKey(BidCacheManager.pub_prefix + item.getSessionId());
		}
		return pub;
	}

	public InterfaceRegister getInterfaceRegister(String reqUrl, String port) {
		InterfaceRegister register = new InterfaceRegister();
		reqUrl = StrUtil.doNull(reqUrl, ToolsUtil.getInstance().getValueByKey("wbd_cache_url"));
		String infoUrl = reqUrl + "/wbd/service/cache/doService";
		if (reqUrl.startsWith("https:")) {
			register.setCallType("https");
			register.setAddress(infoUrl);
		} else if (reqUrl.startsWith("http:")) {
			register.setCallType("http");
			register.setAddress(infoUrl);
		} else {
			port = StrUtil.doNull(port, ToolsUtil.getInstance().getValueByKey("wbd_cache_port"));
			register.setAddress(reqUrl);
			register.setPort(port);
			register.setCallType("socket");
		}
		return register;
	}

	public InterfaceRegister getInterfaceRegister() {
		InterfaceRegister register = new InterfaceRegister();
		String reqUrl = ToolsUtil.getInstance().getValueByKey("wbd_admin_url");
		String infoUrl = reqUrl + "/wbd/service/doService";
		if (reqUrl.startsWith("https:")) {
			register.setCallType("https");
			register.setAddress(infoUrl);
		} else if (reqUrl.startsWith("http:")) {
			register.setCallType("http");
			register.setAddress(infoUrl);
		} else {
			String port = ToolsUtil.getInstance().getValueByKey("wbd_admin_port");
			register.setAddress(reqUrl);
			register.setPort(port);
			register.setCallType("socket");
		}
		return register;
	}

	public String getMergeTime(String sourceTime, String limitTime) {
		String resultTime = "";
		long limittime = Long.valueOf(limitTime) * 1000;
		try {
			Date afterDate = new Date(DateUtils.toLong(DateUtils.parse(sourceTime, "yyyy-MM-dd HH:mm:ss")) + limittime);
			resultTime = DateUtils.format(afterDate, "yyyy-MM-dd HH:mm:ss");
		} catch (ParseException e) {
			long nowTime = DateUtils.strToLong(sourceTime, FmtStr.yyyyMMdd_HHmmss) + limittime;
			resultTime = DateUtils.longToStr(nowTime, FmtStr.yyyyMMdd_HHmmss);
		}
		return resultTime;
	}

	/**
	 * 得到标的应付佣金值(现在还没有计算阶梯的费用)
	 * @param item
	 * @return
	 */
	public double getCommission(String lastValue, String ifFee, BidPub pub) {
		double lastv = Double.parseDouble(StrUtil.doNull(lastValue, "0"));
		if (lastv <= 0) {
			return 0;
		}

		boolean isComm = "T".equals(ifFee);//是否收取服务费	
		if (false == isComm) {
			return 0;
		}

		double commission = Double.parseDouble(StrUtil.doNull(pub.getFeeFix(), "0"));//服务费金额		
		double compercent = Double.parseDouble(StrUtil.doNull(pub.getFeeRate(), "0"));//服务费百分比  

		if (compercent > 0) {//如果未设定百分比，则直接返回佣金值
			commission = lastv * compercent * 0.01;//由百分百计算佣金
			return commission;
			//return commission > 0 ? commission : 0;
		}
		double feeValueMin = Double.parseDouble(StrUtil.doNull(pub.getFeeValueMin(), "0"));
		double feeValueMax = Double.parseDouble(StrUtil.doNull(pub.getFeeValueMax(), "0"));
		if (commission < feeValueMin)
			commission = feeValueMin;
		if (feeValueMax <= 0) {//没有设置最大值
		} else {
			if (commission > feeValueMax)
				commission = feeValueMax;
		}
		return commission;
	}

	/**
	 * 按格式获取毫秒数
	 * @param timeStr
	 * @param formatStr
	 * @return
	 */
	public static long getMillTime(String timeStr, String formatStr) {
		long longTime = 0L;
		try {
			longTime = DateUtils.parse(timeStr, formatStr).getTime();
		} catch (Exception e) {
		}
		return longTime;
	}

}
